package com.test.aidltest;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    //创建ServiceConnection 对象
    //以ServiceConnect对象作为参数,调用那个context的bindService()方法绑定远程service

    private ICat catService;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //获取远程Service的onBind方法返回的代理对象
            catService = ICat.Stub.asInterface(service);
            Log.e("1212", "onServiceConnected: " + catService );
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("1212", "onServiceDisconnected: " + catService + "dis");
            catService = null;
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("1212", "onCreate: " + "111");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView color = findViewById(R.id.color);
        TextView weight = findViewById(R.id.weight);
        Button button = findViewById(R.id.btn1);

        //创建所需绑定Service的Intent
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.test.aidldemo", "com.test.aidldemo.service.AidlService"));
        intent.setAction("com.test.aidl.action.AIDL_SERVICE");

        boolean b = getApplicationContext().bindService(intent, conn, Service.BIND_AUTO_CREATE);
        Log.e("1212", "bindService: " + b );

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    color.setText("姓名:" + catService.getColor());
                    weight.setText("体重:" + catService.getWeight());
                }catch (RemoteException e){
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //接触绑定
        this.unbindService(conn);
    }
}